const { PrismaClient, Prisma } = require('@prisma/client');
const prisma = new PrismaClient();
const formatDateTime = require('../utils/formatDateTime');

/**
 * 获取考试列表用于导出成绩
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 * @returns {Object} 返回包含考试列表和总数的对象
 */
const getBackupList = async (req, res) => {
  try {
    // 获取请求参数
    const { page = 1, pageSize = 10, userId, timeOrder } = req.query;
    
    // 参数验证
    if (!userId) {
      return res.status(400).json({
        code: 400,
        message: '缺少必要的用户ID参数',
        data: null
      });
    }

    // 将用户ID转为整数
    const userIdInt = parseInt(userId);
    
    // 查询用户角色
    const user = await prisma.user.findUnique({
      where: { id: userIdInt },
      select: { role_id: true }
    });
    
    if (!user) {
      return res.status(404).json({
        code: 404,
        message: '用户不存在',
        data: null
      });
    }
    
    // 构建查询条件
    let where = {
      examination_status: '已批阅'
    };
    
    // 根据用户角色构建不同的查询条件
    if (user.role_id === 2) { // 学科组长
      // 查询该学科组长负责的学科
      const subjectLeader = await prisma.teacher_classes_subject.findMany({
        where: { teacher_id: userIdInt },
        select: { subject_id: true },
        distinct: ['subject_id']
      });
      
      const subjectIds = subjectLeader.map(sl => sl.subject_id);
      
      // 查询该学科下的所有"已批阅"的考试
      where.subject_id = { in: subjectIds };
    } else if (user.role_id === 3) { // 教师
      // 查询教师教授的班级和学科
      const teacherClassesSubjects = await prisma.teacher_classes_subject.findMany({
        where: { teacher_id: userIdInt },
        select: { 
          classes_id: true,
          subject_id: true
        }
      });
      
      if (teacherClassesSubjects.length === 0) {
        // 如果教师没有教授任何班级或学科，返回空结果
        return res.status(200).json({
          code: 200,
          message: 'success',
          data: {
            total: 0,
            list: []
          }
        });
      }
      
      const classesIds = teacherClassesSubjects.map(tcs => tcs.classes_id);
      const subjectIds = [...new Set(teacherClassesSubjects.map(tcs => tcs.subject_id))];
      
  
      
      // 先查询所有与教师学科相关的考试
      const examsWithSubject = await prisma.examination.findMany({
        where: {
          examination_status: '已批阅',
          subject_id: { in: subjectIds }
        },
        select: {
          id: true,
          classes_ids: true,
          subject_id: true
        }
      });
      
      // 手动过滤出包含教师班级的考试
      const filteredExams = examsWithSubject.filter(exam => {
        if (!exam.classes_ids) return false;
        
        const examClassesIds = exam.classes_ids.split(',').map(id => parseInt(id.trim()));
        
        // 检查是否有交集
        const hasCommonClass = classesIds.some(classId => 
          examClassesIds.includes(classId)
        );
        
        return hasCommonClass;
      });
      
      
      // 如果没有符合条件的考试，返回空结果
      if (filteredExams.length === 0) {
        return res.status(200).json({
          code: 200,
          message: 'success',
          data: {
            total: 0,
            list: []
          }
        });
      }
      
      // 提取考试ID列表
      const examinationIds = filteredExams.map(e => e.id);
      
      // 在where条件中添加id条件
      where.id = { in: examinationIds };
    } else {
      // 其他角色（如管理员）可以看到所有已批阅的考试
    }

    // 计算分页
    const skip = (parseInt(page) - 1) * parseInt(pageSize);
    const take = parseInt(pageSize);

    // 构建排序条件
    let orderBy = {};
    if (timeOrder) {
      orderBy.end_time = timeOrder === 'desc' ? 'desc' : 'asc';
    } else {
      orderBy.end_time = 'desc'; // 默认按结束时间降序
    }

    // 查询考试总数
    const total = await prisma.examination.count({
      where
    });

    // 查询考试列表
    const examinations = await prisma.examination.findMany({
      where,
      select: {
        id: true,
        name: true,
        examination_type: true,
        end_time: true,
        subject_id: true
      },
      skip,
      take,
      orderBy
    });

    console.log("examinations: ", examinations);

    // 格式化返回数据
    const list = examinations.map(exam => {
      return {
        examinationId: exam.id,
        examinationName: exam.name,
        examinationType: exam.examination_type,
        endTime: formatDateTime(exam.end_time)
      };
    });

    // 返回结果
    return res.status(200).json({
      code: 200,
      message: 'success',
      data: {
        total,
        list
      }
    });
  } catch (error) {
    console.error('获取考试列表失败:', error);
    return res.status(500).json({
      code: 500,
      message: '获取考试列表失败',
      data: null
    });
  }
};

/**
 * 根据用户ID获取班级列表
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 * @returns {Object} 返回包含班级列表的数组
 */
const getClassesByUserId = async (req, res) => {
  try {
    // 获取请求参数
    const { userId, examinationId } = req.query;
    
    // 参数验证
    if (!userId || !examinationId) {
      return res.status(400).json({
        code: 400,
        message: '缺少必要参数',
        data: null
      });
    }

    // 将参数转为整数
    const userIdInt = parseInt(userId);
    const examinationIdInt = parseInt(examinationId);

    // 查询考试信息，获取学科ID
    const examination = await prisma.examination.findUnique({
      where: { id: examinationIdInt },
      select: { subject_id: true, classes_ids: true }
    });

    if (!examination) {
      return res.status(404).json({
        code: 404,
        message: '考试不存在',
        data: null
      });
    }

    // 获取考试关联的班级ID列表
    const examClassIds = examination.classes_ids 
      ? examination.classes_ids.split(',').map(id => parseInt(id)) 
      : [];


    // 查询用户角色
    const user = await prisma.user.findUnique({
      where: { id: userIdInt },
      select: { role_id: true }
    });

    if (!user) {
      return res.status(404).json({
        code: 404,
        message: '用户不存在',
        data: null
      });
    }

    let classesIds = [];

    // 根据角色获取班级
    if (user.role_id === 3) {
      // 教师：查找自己教授的班级，并且参加了这场考试的班级
      const teacherClasses = await prisma.teacher_classes_subject.findMany({
        where: {
          teacher_id: userIdInt,
          subject_id: examination.subject_id
        },
        select: { classes_id: true }
      });
      
      const teacherClassIds = teacherClasses.map(tc => tc.classes_id);
      
      // 取交集：教师教授的班级与参加考试的班级的交集
      classesIds = teacherClassIds.filter(id => examClassIds.includes(id));
    } else if (user.role_id === 2) {
      // 学科组长：查找选了该学科的所有班级，并且参加了这场考试的班级
      const subjectClasses = await prisma.teacher_classes_subject.findMany({
        where: { subject_id: examination.subject_id },
        select: { classes_id: true },
        distinct: ['classes_id'] // 去重
      });
      
      const subjectClassIds = subjectClasses.map(sc => sc.classes_id);
      
      
      // 取交集：选了该学科的班级与参加考试的班级的交集
      classesIds = subjectClassIds.filter(id => examClassIds.includes(id));
    } else {
      // 其他角色（如管理员）可以看到所有参加这场考试的班级
      classesIds = examClassIds;
    }

    // 查询班级详细信息
    const classes = await prisma.classes.findMany({
      where: {
        id: { in: classesIds }
      },
      select: {
        id: true,
        name: true
      }
    });

    console.log("classes: ",classes);

    // 格式化返回数据
    const formattedClasses = classes.map(cls => {
      return {
        classesId: cls.id,
        classesName: cls.name
      };
    });

    // 返回结果
    return res.status(200).json({
      code: 200,
      message: 'success',
      data: formattedClasses
    });
  } catch (error) {
    console.error('获取班级列表失败:', error);
    return res.status(500).json({
      code: 500,
      message: '获取班级列表失败',
      data: null
    });
  }
};

/**
 * 获取特定考试和班级的学生试卷信息
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 * @returns {Object} 返回包含学生试卷信息的数组
 */
const getStudentPaper = async (req, res) => {
  try {
    // 获取请求参数
    const { examinationId, classesIds } = req.body;
    
    // 参数验证
    if (!examinationId || !classesIds) {
      return res.status(400).json({
        code: 400,
        message: '缺少必要参数',
        data: null
      });
    }

    // 将参数转为整数
    const examinationIdInt = parseInt(examinationId);
    const classesIdsArray = classesIds.map(id => parseInt(id));

    // 查询考试是否存在
    const examination = await prisma.examination.findUnique({
      where: { id: examinationIdInt },
      select: {
        id: true,
        name: true
      }
    });

    if (!examination) {
      return res.status(404).json({
        code: 404,
        message: '考试不存在',
        data: null
      });
    }

    // 查询符合条件的学生试卷信息
    // 由于Prisma模型关系设置的原因，需要分步查询
    
    // 1. 先获取指定班级的学生ID列表
    const studentsInClasses = await prisma.student_classes.findMany({
      where: {
        classes_id: { in: classesIdsArray }
      },
      select: {
        student_id: true,
        classes_id: true
      }
    });

    // 提取学生ID列表
    const studentIds = studentsInClasses.map(record => record.student_id);
    
    // 2. 查询班级信息
    const classes = await prisma.classes.findMany({
      where: {
        id: { in: classesIdsArray }
      },
      select: {
        id: true,
        name: true
      }
    });
    
    // 创建班级ID到班级名称的映射
    const classesMap = {};
    classes.forEach(cls => {
      classesMap[cls.id] = cls.name;
    });

    // 3. 查询这些学生在特定考试中的试卷
    const studentPapers = await prisma.student_paper.findMany({
      where: {
        examination_id: examinationIdInt,
        user_id: { in: studentIds }
      },
      select: {
        id: true,
        user_id: true,
        total_score: true
      }
    });

    // 4. 获取学生信息
    const students = await prisma.user.findMany({
      where: {
        id: { in: studentIds }
      },
      select: {
        id: true,
        name: true
      }
    });

    // 创建学生ID到学生姓名的映射
    const studentsMap = {};
    students.forEach(student => {
      studentsMap[student.id] = student.name;
    });
    
    // 创建学生ID到班级ID的映射
    const studentToClassMap = {};
    studentsInClasses.forEach(record => {
      studentToClassMap[record.student_id] = record.classes_id;
    });

    // 整合数据
    const formattedStudentPapers = studentPapers.map(paper => {
      const studentId = paper.user_id;
      const classesId = studentToClassMap[studentId];
      
      return {
        studentPaperId: paper.id,
        classesName: classesMap[classesId] || '未知班级',
        studentName: studentsMap[studentId] || '未知学生',
        score: paper.total_score || 0,
        examinationName: examination.name || '未知考试'
      };
    });

    // 按班级名称和学生分数降序排序
    formattedStudentPapers.sort((a, b) => {
      return b.score - a.score; // 按分数降序排列
    });

    // 添加sort属性，从1开始
    formattedStudentPapers.forEach((paper, index) => {
      paper.sort = index + 1;
    });

    // 返回结果
    return res.status(200).json({
      code: 200,
      message: 'success',
      data: formattedStudentPapers
    });
  } catch (error) {
    console.error('获取学生试卷信息失败:', error);
    return res.status(500).json({
      code: 500,
      message: '获取学生试卷信息失败',
      data: null
    });
  }
};


/**
 * 获取知识点得分率分析数据
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 * @returns {Object} 返回知识点得分率分析数据
 */
const getKnowledgePointRate = async (req, res) => {
  try {
    // 获取请求参数
    const { examinationId, classesId = 0 } = req.query;
 

    // 参数验证
    if (!examinationId) {
      return res.status(400).json({
        code: 400,
        message: '缺少必要参数',
        data: null
      });
    }

    const examinationIdInt = parseInt(examinationId);
    const classesIdInt = parseInt(classesId);

    // 获取考试信息
    const examination = await prisma.examination.findUnique({
      where: { id: examinationIdInt }
    });

    if (!examination) {
      return res.status(404).json({
        code: 404,
        message: '考试不存在',
        data: null
      });
    }

    // 获取参与该考试的学生ID列表
    let studentIds = [];
    
    if (classesIdInt > 0) {
      // 如果指定班级，则获取该班级参与考试的学生
      const studentsInClass = await prisma.student_classes.findMany({
        where: { classes_id: classesIdInt },
        select: { student_id: true }
      });
      
      studentIds = studentsInClass.map(record => record.student_id);
    } else {
      // 如果未指定班级，则获取所有参与考试的班级
      const classesIdsArray = examination.classes_ids 
        ? examination.classes_ids.split(',').map(id => parseInt(id)) 
        : [];
      
      // 获取这些班级的所有学生
      const studentsInClasses = await prisma.student_classes.findMany({
        where: { classes_id: { in: classesIdsArray } },
        select: { student_id: true }
      });
      
      studentIds = studentsInClasses.map(record => record.student_id);
    }

    // 获取这些学生在本次考试中的试卷
    const studentPapers = await prisma.student_paper.findMany({
      where: {
        examination_id: examinationIdInt,
        user_id: { in: studentIds },
        examination_status: { not: null } // 已批阅的试卷
      },
      select: {
        id: true,
        user_id: true
      }
    });

    const studentPaperIds = studentPapers.map(paper => paper.id);

    // 获取试卷详情
    const paperDetails = await prisma.paper_detail.findMany({
      where: { student_paper_id: { in: studentPaperIds } },
      select: {
        id: true,
        student_paper_id: true,
        question_id: true,
        final_score: true,
        score: true
      }
    });

    // 获取试题信息
    const questionIds = [...new Set(paperDetails.map(detail => detail.question_id))];
    
    const questions = await prisma.question.findMany({
      where: { id: { in: questionIds } },
      select: {
        id: true,
        knowledge_point_id: true,
        answer_type_id: true
      }
    });

    // 构建知识点与试题的映射
    const questionMap = {};
    questions.forEach(q => {
      if (q.knowledge_point_id) {
        questionMap[q.id] = {
          knowledgePointId: q.knowledge_point_id,
          answerTypeId: q.answer_type_id
        };
      }
    });

    // 获取最后一级知识点（没有子知识点的知识点）
    const allKnowledgePoints = await prisma.knowledge_point.findMany({
      where: { subject_id: examination.subject_id },
      select: {
        id: true,
        name: true,
        parent_id: true
      }
    });

    // 找出所有知识点ID
    const allKnowledgePointIds = allKnowledgePoints.map(kp => kp.id);
    
    // 找出有子节点的知识点ID
    const parentKnowledgePointIds = allKnowledgePoints
      .filter(kp => kp.parent_id !== null)
      .map(kp => kp.parent_id);
    
    // 最后一级知识点 = 所有知识点 - 有子节点的知识点
    const leafKnowledgePointIds = allKnowledgePointIds.filter(id => !parentKnowledgePointIds.includes(id));
    
    // 过滤得到最后一级知识点信息
    const leafKnowledgePoints = allKnowledgePoints.filter(kp => leafKnowledgePointIds.includes(kp.id));

    // 创建知识点ID到名称的映射
    const knowledgePointMap = {};
    leafKnowledgePoints.forEach(kp => {
      knowledgePointMap[kp.id] = kp.name;
    });

    // 获取该考试中的试题满分
    const examPlanDetails = await prisma.exam_plan_details.findMany({
      where: { exam_plan_id: examination.exam_plan_id },
      select: {
        knowledge_point_id: true,
        score: true
      }
    });

    // 构建知识点满分映射
    const knowledgePointMaxScoreMap = {};
    examPlanDetails.forEach(detail => {
      if (detail.knowledge_point_id) {
        if (!knowledgePointMaxScoreMap[detail.knowledge_point_id]) {
          knowledgePointMaxScoreMap[detail.knowledge_point_id] = 0;
        }
        knowledgePointMaxScoreMap[detail.knowledge_point_id] += detail.score || 0;
      }
    });

    // 统计每个知识点的得分情况
    const knowledgePointStats = {};
    
    paperDetails.forEach(detail => {
      const questionInfo = questionMap[detail.question_id];
      if (!questionInfo) return;
      
      const knowledgePointId = questionInfo.knowledgePointId;
      if (!knowledgePointId || !leafKnowledgePointIds.includes(knowledgePointId)) return;
      
      if (!knowledgePointStats[knowledgePointId]) {
        knowledgePointStats[knowledgePointId] = {
          totalScore: 0,
          count: 0,
          maxPossibleScore: knowledgePointMaxScoreMap[knowledgePointId] || 0
        };
      }
      
      knowledgePointStats[knowledgePointId].totalScore += detail.final_score || 0;
      knowledgePointStats[knowledgePointId].count++;
    });

    // 计算每个知识点的得分率
    const knowledgePointRates = Object.keys(knowledgePointStats).map(knowledgePointId => {
      const stats = knowledgePointStats[knowledgePointId];
      const averageScore = stats.count > 0 ? stats.totalScore / stats.count : 0;
      // 修改得分率计算公式：得分率 = (所有学生在该知识点题目的总得分) / (所有学生该知识点题目的总满分) × 100%
      const totalStudents = studentPapers.length;
      // 该知识点的总满分 = 知识点满分 × 学生人数
      const totalPossibleScore = stats.maxPossibleScore * totalStudents;
      const scoreRate = totalPossibleScore > 0 ? (stats.totalScore / totalPossibleScore)  : 0;
      
      return {
        knowledgePointId: parseInt(knowledgePointId),
        knowledgePointName: knowledgePointMap[knowledgePointId] || '未知知识点',
        averageScore: parseFloat(averageScore.toFixed(2)),
        maxScore: stats.maxPossibleScore,
        scoreRate: parseFloat(scoreRate.toFixed(2)),
        count: stats.count,
        studentCount: totalStudents
      };
    });

    // 按得分率升序排序（得分率低的知识点需要关注）
    knowledgePointRates.sort((a, b) => a.scoreRate - b.scoreRate);

    return res.status(200).json({
      code: 200,
      message: 'success',
      data: knowledgePointRates
    });
  } catch (error) {
    console.error('获取知识点得分率分析数据失败:', error);
    return res.status(500).json({
      code: 500,
      message: '获取知识点得分率分析数据失败',
      data: null
    });
  }
};

/**
 * 获取试题质量分析数据
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 * @returns {Object} 返回试题质量分析数据
 */
const getQuestionQuality = async (req, res) => {
  try {
    // 获取请求参数
    const { examinationId, classesId = 0 } = req.query;
    
    // 参数验证
    if (!examinationId) {
      return res.status(400).json({
        code: 400,
        message: '缺少必要参数',
        data: null
      });
    }

    const examinationIdInt = parseInt(examinationId);
    const classesIdInt = parseInt(classesId);

    // 获取考试信息
    const examination = await prisma.examination.findUnique({
      where: { id: examinationIdInt },
      select: {
        id: true,
        name: true,
        exam_plan_id: true,
        subject_id: true,
        classes_ids: true
      }
    });

    if (!examination) {
      return res.status(404).json({
        code: 404,
        message: '考试不存在',
        data: null
      });
    }

    if (!examination.exam_plan_id) {
      return res.status(404).json({
        code: 404,
        message: '考试计划不存在',
        data: null
      });
    }

    // 获取参与该考试的学生ID列表
    let studentIds = [];
    
    if (classesIdInt > 0) {
      // 如果指定班级，则获取该班级参与考试的学生
      const studentsInClass = await prisma.student_classes.findMany({
        where: { classes_id: classesIdInt },
        select: { student_id: true }
      });
      
      studentIds = studentsInClass.map(record => record.student_id);
    } else {
      // 如果未指定班级，则获取所有参与考试的班级
      const classesIdsArray = examination.classes_ids 
        ? examination.classes_ids.split(',').map(id => parseInt(id)) 
        : [];
      
      // 获取这些班级的所有学生
      const studentsInClasses = await prisma.student_classes.findMany({
        where: { classes_id: { in: classesIdsArray } },
        select: { student_id: true }
      });
      
      studentIds = studentsInClasses.map(record => record.student_id);
    }

    // 获取这些学生在本次考试中的试卷
    const studentPapers = await prisma.student_paper.findMany({
      where: {
        examination_id: examinationIdInt,
        user_id: { in: studentIds },
        examination_status: { not: null } // 已批阅的试卷
      },
      select: {
        id: true,
        user_id: true
      }
    });

    if (studentPapers.length === 0) {
      return res.status(200).json({
        code: 200,
        message: 'success',
        data: []
      });
    }

    const studentPaperIds = studentPapers.map(paper => paper.id);

    // 获取试卷详情
    const paperDetails = await prisma.paper_detail.findMany({
      where: { student_paper_id: { in: studentPaperIds } },
      select: {
        id: true,
        student_paper_id: true,
        question_id: true,
        final_score: true,
        score: true
      }
    });

    // 获取试题ID列表
    const questionIds = [...new Set(paperDetails.map(detail => detail.question_id))];
    
    if (questionIds.length === 0) {
      return res.status(200).json({
        code: 200,
        message: 'success',
        data: []
      });
    }

    // 获取试题详细信息
    const questions = await prisma.question.findMany({
      where: { id: { in: questionIds } },
      select: {
        id: true,
        knowledge_point_id: true,
        question_type_id: true,
        name: true,
        big_question_id: true
      }
    });

    // 获取知识点信息
    const knowledgePointIds = questions
      .filter(q => q.knowledge_point_id)
      .map(q => q.knowledge_point_id);

    const knowledgePoints = await prisma.knowledge_point.findMany({
      where: { id: { in: knowledgePointIds } },
      select: {
        id: true,
        name: true
      }
    });

    // 创建知识点ID到名称的映射
    const knowledgePointMap = {};
    knowledgePoints.forEach(kp => {
      knowledgePointMap[kp.id] = kp.name;
    });

    // 获取题型信息
    const questionTypeIds = [...new Set(questions.map(q => q.question_type_id))];
    
    const questionTypes = await prisma.question_type.findMany({
      where: { id: { in: questionTypeIds } },
      select: {
        id: true,
        name: true
      }
    });

    // 创建题型ID到名称的映射
    const questionTypeMap = {};
    questionTypes.forEach(qt => {
      questionTypeMap[qt.id] = qt.name;
    });
    
    // 获取大题信息
    const bigQuestionIds = [...new Set(questions
      .filter(q => q.big_question_id)
      .map(q => q.big_question_id))];
      
    const bigQuestions = await prisma.big_question.findMany({
      where: { id: { in: bigQuestionIds } },
      select: {
        id: true,
        name: true
      }
    });
    
    // 创建大题ID到名称的映射
    const bigQuestionMap = {};
    bigQuestions.forEach(bq => {
      bigQuestionMap[bq.id] = bq.name;
    });

    // 获取试题的满分信息 - 从paper_detail中获取question_order
    const paperDetailsWithOrder = await prisma.paper_detail.findMany({
      where: { student_paper_id: { in: studentPaperIds }, question_id: { in: questionIds } },
      select: {
        question_id: true,
        question_order: true
      },
      distinct: ['question_id', 'question_order']
    });
    
    // 创建问题ID到题号的映射
    const questionToOrderMap = {};
    paperDetailsWithOrder.forEach(detail => {
      if (!questionToOrderMap[detail.question_id]) {
        questionToOrderMap[detail.question_id] = detail.question_order;
      }
    });
    
    // 获取组卷方案详情，包含各题的满分
    const examPlanDetails = await prisma.exam_plan_details.findMany({
      where: { exam_plan_id: examination.exam_plan_id },
      select: {
        question_order: true,
        score: true
      }
    });
    
    // 创建题号到满分的映射
    const orderToScoreMap = {};
    examPlanDetails.forEach(detail => {
      if (detail.question_order) {
        orderToScoreMap[detail.question_order] = detail.score || 0;
      }
    });
    
    // 创建试题ID到满分的映射
    const questionScoreMap = {};
    
    // 为每个试题关联对应题号的分值
    questions.forEach(question => {
      const questionOrder = questionToOrderMap[question.id];
      if (questionOrder && orderToScoreMap[questionOrder]) {
        questionScoreMap[question.id] = orderToScoreMap[questionOrder];
      } else {
        // 如果找不到关联的题号和分值，默认为0分
        questionScoreMap[question.id] = 0;
      }
    });

    // 构建每道题的得分统计
    const questionStats = {};
    
    paperDetails.forEach(detail => {
      const questionId = detail.question_id;
      
      if (!questionStats[questionId]) {
        questionStats[questionId] = {
          totalScore: 0,
          totalStudents: 0,
          scoreDistribution: {
            excellent: 0, // 优秀（得分率>=90%）
            good: 0,      // 良好（得分率>=75% 且 <90%）
            average: 0,   // 中等（得分率>=60% 且 <75%）
            poor: 0,      // 较差（得分率>=30% 且 <60%）
            fail: 0       // 不及格（得分率<30%）
          }
        };
      }
      
      const stats = questionStats[questionId];
      const score = detail.final_score || 0;   // 学生得分
      const maxScore = questionScoreMap[questionId] || 1; // 防止除以0
      const scoreRate = (score / maxScore) * 100;
      
      stats.totalScore += score;
      stats.totalStudents += 1;
      
      // 按得分率分布统计
      if (scoreRate >= 90) {
        stats.scoreDistribution.excellent += 1;
      } else if (scoreRate >= 75) {
        stats.scoreDistribution.good += 1;
      } else if (scoreRate >= 60) {
        stats.scoreDistribution.average += 1;
      } else if (scoreRate >= 30) {
        stats.scoreDistribution.poor += 1;
      } else {
        stats.scoreDistribution.fail += 1;
      }
    });

    // 计算每道题的质量指标
    const questionQualityData = [];
    
    questions.forEach(question => {
      const questionId = question.id;
      const stats = questionStats[questionId] || { totalScore: 0, totalStudents: 0 };
      const maxScore = questionScoreMap[questionId] || 0;
      
      if (stats.totalStudents === 0) return; // 跳过没有学生回答的题目
      
      // 计算平均分
      const averageScore = stats.totalScore / stats.totalStudents;
      
      // 计算难度系数 = 平均得分率 = 平均分 / 满分
      const difficultyCoefficient = maxScore > 0 ? averageScore / maxScore : 0;
      
      // 判断试题质量
      let quality;
      if (difficultyCoefficient >= 0.85) {
        quality = '易';
      } else if (difficultyCoefficient >= 0.65) {
        quality = '中';
      } else if (difficultyCoefficient >= 0.35) {
        quality = '适中';
      } else if (difficultyCoefficient >= 0.15) {
        quality = '难';
      } else {
        quality = '极难';
      }
      
      // 判断是否异常（极易或极难都可能是试题设计有问题）
      const isAbnormal = difficultyCoefficient > 0.95 || difficultyCoefficient < 0.10;
      
      // 构建返回数据
      questionQualityData.push({
        questionId,
        questionName: question.name || '未知题名',
        knowledgePointName: question.knowledge_point_id ? knowledgePointMap[question.knowledge_point_id] || '未知知识点' : '未知知识点',
        questionTypeName: question.question_type_id ? questionTypeMap[question.question_type_id] || '未知题型' : '未知题型',
        bigQuestionName: question.big_question_id ? bigQuestionMap[question.big_question_id] || '未知大题' : '未知大题',
        averageScore: parseFloat(averageScore.toFixed(2)),
        maxScore,
        difficultyCoefficient: parseFloat(difficultyCoefficient.toFixed(2)),
        quality,
        isAbnormal,
        scoreDistribution: stats.scoreDistribution,
        totalStudents: stats.totalStudents
      });
    });

    // 按难度系数升序排序（由难到易）
    questionQualityData.sort((a, b) => a.difficultyCoefficient - b.difficultyCoefficient);

    // 生成试题异常报告
    const abnormalQuestions = questionQualityData.filter(q => q.isAbnormal);

    
    const now = new Date();
    const utc8Date = new Date(now.getTime() + (8 * 60 * 60 * 1000));

    if (abnormalQuestions.length > 0) {
      try {
        // 检查是否已存在该考试的报告
        const existingReport = await prisma.question_analysis_report.findFirst({
          where: {
            examination_id: examinationIdInt,
            classes_id: classesIdInt
          }
        });
    
        let reportId;
        
        if (existingReport) {
          // 更新已有报告
          await prisma.question_analysis_report.update({
            where: { id: existingReport.id },
            data: {
              abnormal_count: abnormalQuestions.length,
              updated_at: utc8Date
            }
          });
          reportId = existingReport.id;
          
          // 删除旧的详情记录
          await prisma.question_anomaly_detail.deleteMany({
            where: { report_id: reportId }
          });
        } else {
          // 创建新报告
          const newReport = await prisma.question_analysis_report.create({
            data: {
              examination_id: examinationIdInt,
              classes_id: classesIdInt,
              abnormal_count: abnormalQuestions.length,
              created_at: utc8Date
            }
          });
          reportId = newReport.id;
        }
        
        // 创建异常试题详情记录
        const anomalyDetailPromises = abnormalQuestions.map(question => {
          let suggestion;
          if(question.difficultyCoefficient < 0.10){
            suggestion = '建议复审或删除该题目';
          }else if(question.difficultyCoefficient > 0.95){
            suggestion = '建议提高试题难度';
          }
            
          return prisma.question_anomaly_detail.create({
            data: {
              report_id: reportId,
              examination_id: examinationIdInt,
              question_id: question.questionId,
              knowledge_point_id: questions.find(q => q.id === question.questionId)?.knowledge_point_id || null,
              difficulty_coefficient: question.difficultyCoefficient,
              quality_level: question.quality,
              suggestion: suggestion,
              updated_at: utc8Date
            }
          });
        });
        
        // 批量创建异常详情记录
        await Promise.all(anomalyDetailPromises);
    
   
    
        return res.status(200).json({
          code: 200,
          message: 'success',
          data: questionQualityData
        });
      } catch (error) {
        console.error('生成试题异常报告失败:', error);
        // 即使报告生成失败，仍然返回试题质量数据
        return res.status(200).json({
          code: 200,
          message: 'success',
          data: questionQualityData
        });
      }
    } else {
      // 没有异常试题，不需要生成报告
      return res.status(200).json({
        code: 200,
        message: 'success',
        data: questionQualityData
      });
    }
    

  } catch (error) {
    console.error('获取试题质量分析数据失败:', error);
    return res.status(500).json({
      code: 500,
      message: '获取试题质量分析数据失败',
      data: null
    });
  }
};

/**
 * 根据考试ID获取考试信息和学生成绩
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 * @returns {Object} 返回包含考试信息和学生成绩的对象
 */
const getExaminationAndStudentScore = async (req, res) => {
  try {
    // 获取请求参数
    const { examinationId, classesId = 0 } = req.body;
    
    // 参数验证
    if (!examinationId) {
      return res.status(400).json({
        code: 400,
        message: '缺少必要参数',
        data: null
      });
    }

    // 将参数转为整数
    const examinationIdInt = parseInt(examinationId);
    const classesIdInt = parseInt(classesId);

    // 查询考试信息
    const examination = await prisma.examination.findUnique({
      where: { id: examinationIdInt },
      select: {
        id: true,
        name: true,
        start_time: true,
        end_time: true,
        exam_plan_id: true,
        classes_ids: true
      }
    });

    if (!examination) {
      return res.status(404).json({
        code: 404,
        message: '考试不存在',
        data: null
      });
    }

    // 获取考试满分
    let fullMark = 0;
    if (examination.exam_plan_id) {
      const examPlanDetails = await prisma.exam_plan_details.findMany({
        where: { exam_plan_id: examination.exam_plan_id },
        select: { score: true }
      });
      
      fullMark = examPlanDetails.reduce((total, detail) => total + (detail.score || 0), 0);
    }

    // 获取参与此次考试的班级ID列表
    let classesIds = [];
    if (classesIdInt > 0) {
      // 如果指定了班级ID，就只查询该班级
      classesIds.push(classesIdInt);
    } else {
      // 否则查询所有参与此次考试的班级
      classesIds = examination.classes_ids 
        ? examination.classes_ids.split(',').map(id => parseInt(id))
        : [];
    }

    // 获取班级信息
    const classes = await prisma.classes.findMany({
      where: {
        id: { in: classesIds }
      },
      select: {
        id: true,
        name: true
      }
    });

    // 创建班级ID到班级名称的映射
    const classesMap = {};
    classes.forEach(cls => {
      classesMap[cls.id] = cls.name;
    });

    // 获取这些班级的学生
    const studentsInClasses = await prisma.student_classes.findMany({
      where: {
        classes_id: { in: classesIds }
      },
      select: {
        student_id: true,
        classes_id: true
      }
    });

    // 提取学生ID列表
    const studentIds = [...new Set(studentsInClasses.map(record => record.student_id))];

    // 创建学生ID到班级ID的映射
    const studentToClassMap = {};
    studentsInClasses.forEach(record => {
      studentToClassMap[record.student_id] = record.classes_id;
    });

    // 获取学生信息
    const students = await prisma.user.findMany({
      where: {
        id: { in: studentIds }
      },
      select: {
        id: true,
        name: true,
        account: true
      }
    });

    // 创建学生ID到学生信息的映射
    const studentMap = {};
    students.forEach(student => {
      studentMap[student.id] = {
        name: student.name,
        account: student.account
      };
    });

    // 获取学生试卷信息
    const studentPapers = await prisma.student_paper.findMany({
      where: {
        examination_id: examinationIdInt,
        user_id: { in: studentIds },
        examination_status: { not: null } // 只查询已批阅的试卷
      },
      select: {
        id: true,
        user_id: true,
        total_score: true
      }
    });

    // 计算平均分
    let totalScore = 0;
    studentPapers.forEach(paper => {
      totalScore += paper.total_score || 0;
    });
    const avgScore = studentPapers.length > 0 ? parseFloat((totalScore / studentPapers.length).toFixed(2)) : 0;

    // 格式化学生成绩数据
    const studentScores = studentPapers.map(paper => {
      const studentId = paper.user_id;
      const classesId = studentToClassMap[studentId];
      const student = studentMap[studentId] || { name: '未知', account: '未知' };
      
      return {
        classesName: classesMap[classesId] || '未知班级',
        studentAccount: student.account || '未知学号',
        studentName: student.name || '未知姓名',
        score: paper.total_score || 0
      };
    });

    // 按班级名称和学生姓名排序
    studentScores.sort((a, b) => {
      return b.score - a.score;
    });

    // 构建返回数据
    const formattedExamination = {
      examinationId: examination.id,
      examinationName: examination.name,
      startTime: formatDateTime(examination.start_time),
      endTime: formatDateTime(examination.end_time),
      fullMark: fullMark,
      avgScore: avgScore
    };

    // 返回结果
    return res.status(200).json({
      code: 200,
      message: 'success',
      data: {
        examination: formattedExamination,
        studentScore: studentScores
      }
    });
  } catch (error) {
    console.error('获取考试信息和学生成绩失败:', error);
    return res.status(500).json({
      code: 500,
      message: '获取考试信息和学生成绩失败',
      data: null
    });
  }
};

/**
 * 根据考试ID和班级ID获取异常题目信息
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 * @returns {Object} 返回包含考试信息和异常试题信息的对象
 */
const getAbnormalQuestion = async (req, res) => {
  try {
    // 获取请求参数
    const { examinationId, classesId = 0 } = req.query;
    
    // 参数验证
    if (!examinationId) {
      return res.status(400).json({
        code: 400,
        message: '缺少必要参数',
        data: null
      });
    }

    const examinationIdInt = parseInt(examinationId);
    const classesIdInt = parseInt(classesId);

    // 获取考试信息
    const examination = await prisma.examination.findUnique({
      where: { id: examinationIdInt },
      select: {
        id: true,
        name: true,
        start_time: true,
        end_time: true,
        exam_plan_id: true,
        subject_id: true
      }
    });

    if (!examination) {
      return res.status(404).json({
        code: 404,
        message: '考试不存在',
        data: null
      });
    }

    // 查询是否有分析报告
    const report = await prisma.question_analysis_report.findFirst({
      where: {
        examination_id: examinationIdInt,
        classes_id: classesIdInt
      },
      select: {
        id: true,
        abnormal_count: true
      }
    });

    if (!report) {
      return res.status(200).json({
        code: 200,
        message: 'success',
        data: {
          examination: {
            examinationName: examination.name,
            startTime: formatDateTime(examination.start_time),
            endTime: formatDateTime(examination.end_time)
          },
          abnormalQuestions: []
        }
      });
    }

    // 查询异常题目详情
    const abnormalDetails = await prisma.question_anomaly_detail.findMany({
      where: {
        report_id: report.id
      },
      select: {
        question_id: true,
        difficulty_coefficient: true,
        quality_level: true,
        suggestion: true
      }
    });

    if (abnormalDetails.length === 0) {
      return res.status(200).json({
        code: 200,
        message: 'success',
        data: {
          examination: {
            examinationName: examination.name,
            startTime: formatDateTime(examination.start_time),
            endTime: formatDateTime(examination.end_time)
          },
          abnormalQuestions: []
        }
      });
    }

    // 获取试题信息
    const questionIds = abnormalDetails.map(detail => detail.question_id);
    
    const questions = await prisma.question.findMany({
      where: { id: { in: questionIds } },
      select: {
        id: true,
        name: true,
        big_question_id: true
      }
    });

    // 获取大题信息
    const bigQuestionIds = [...new Set(questions
      .filter(q => q.big_question_id)
      .map(q => q.big_question_id))];
      
    const bigQuestions = await prisma.big_question.findMany({
      where: { id: { in: bigQuestionIds } },
      select: {
        id: true,
        name: true
      }
    });
    
    // 创建大题ID到名称的映射
    const bigQuestionMap = {};
    bigQuestions.forEach(bq => {
      bigQuestionMap[bq.id] = bq.name;
    });

    // 构建返回数据
    const abnormalQuestions = abnormalDetails.map(detail => {
      const question = questions.find(q => q.id === detail.question_id) || {};
      return {
        questionName: question.name || '未知题名',
        bigQuestionName: question.big_question_id ? bigQuestionMap[question.big_question_id] || '未知大题' : '未知大题',
        difficultyCoefficient: detail.difficulty_coefficient,
        qualityLevel: detail.quality_level,
        suggestion: detail.suggestion
      };
    });

    return res.status(200).json({
      code: 200,
      message: 'success',
      data: {
        examination: {
          examinationName: examination.name,
          startTime: formatDateTime(examination.start_time),
          endTime: formatDateTime(examination.end_time)
        },
        abnormalQuestions
      }
    });
  } catch (error) {
    console.error('获取异常题目信息失败:', error);
    return res.status(500).json({
      code: 500,
      message: '获取异常题目信息失败',
      data: null
    });
  }
};

module.exports = {
  getBackupList,
  getClassesByUserId,
  getStudentPaper,
  getKnowledgePointRate,
  getQuestionQuality,
  getExaminationAndStudentScore,
  getAbnormalQuestion
}; 